<?php
/**登录接口
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/12
 * Time: 17:10
 */
namespace app\index\controller;

use PHPMailer\SendEmail;
use think\Controller;
use app\common\model\UserType;
use app\common\model\ManagerPassword as ManagerPasswordModel;
use org\Verify;
use think\Db;

/**
 * 登录控制器
 * Class Login
 * @package app\index\controller
 */
class Login extends Controller
{
    public function getIndex()
    {
//        $oos = config('oos');
//        return admin_json(1,'od',$oos);
//        var_dump($oos);die;
//        $result = SendEmail::SendEmail();
//
//        if($result){
//            //发送成功的处理逻辑
//            echo 1;
//        }else{
//            //发送失败的处理逻辑
//            echo 2;
//        }
//        $module     = strtolower(request()->module());
//        $controller = strtolower(request()->controller());
//        $action     = strtolower(request()->action());
//        $url        = $module."/".$controller."/".$action;
//        echo $url;die;
//        echo '<pre>';
//        print_r(session('name'));die;
        return $this->fetch('role/index');
    }

    /**
     * [doLogin  登录操作]
     * @author [C。]
     * @return json
     */
    public function postDoLogin()
    {
        $username = input("param.username");
        $password = input("param.password");
        $code = input("param.code");
        $comid = input("param.comid");

        //compact()创建一个包含变量名和它们的值的数组：  Array ( [username] => $username [password] => $password )
        $result = $this->validate(compact('username', 'password','code'), 'Manager');
        if(true !== $result){
            return admin_json(-6,$result);
        }

        $verify = new Verify();
        $verify->seKey = config('index.verify_halt'); // 自定义验证码加密密钥

        if (!$verify->check($code))
            return admin_json(-4,'验证码错误');

        $hasUser = Db::name('manager_password')->field('id,mid,tel,password,states,loginnum')->where(['tel'=>$username,'comid'=>$comid])->find();

        if(empty($hasUser)){
            return admin_json(-1,'管理员不存在');
        }
        if($hasUser['states'] == -1){
            return admin_json(-1,'已不是管理员');
        }
        if(md5(md5($password) . config('index.manager_password_halt')) != $hasUser['password']){
            writelog($hasUser['mid'],$comid,'管理员【'.$hasUser['tel'].'】登录失败：密码错误',-1);
            return admin_json(-2,'账号或密码错误');
        }

        if($hasUser['states'] == 2){
            writelog($hasUser['mid'],$comid,'管理员【'.$hasUser['tel'].'】登录失败：该账号被禁用',-1);
            return admin_json(-7,'该账号被禁用');
        }

        //更新管理员状态
        $param = [
            'loginnum' => $hasUser['loginnum'] + 1,
            'last_login_ip' => request()->ip(),
            'last_login_time' => time(),
            'update_time' => time(),
            'token' => md5($hasUser['tel'] . $hasUser['password'].$comid.time())
        ];

        Db::name('manager_password')->where('id', $hasUser['id'])->update($param);
        writelog($hasUser['mid'],$comid,'管理员【'.$hasUser['tel'].'】登录成功');

        return admin_json(1,'登录成功',['token'=>$param['token']]);
    }
    /**
     * [getCode 获取验证码]
     * @param
     * @author [C。]
     * @return json
     */
    public function postCode()
    {
        $param = input('param.');
        $tel = $param['tel'];
        $code = randString();
        $mem = Db::name('manager')->where('tel',$param['tel'])->find();
        $result = demo_sendsms($tel,$code);
        if ($result && 'OK' == $result['Code']) {
            $data = array(
                'tel' => $tel,
                'code' => $code,
                'type' => 4,
                'addtime' =>time()
            );
            Db::name('vercode')->insert($data);
            writelog($mem['id'],$param['comid'],'验证码发送成功'.$tel);
            return admin_json('1','验证码已发送');
        }else{
            writelog($mem['id'],$param['comid'],'验证码发送失败'.$tel);
            return admin_json('-1','请稍后再试！');
        }
    }
    /**
     * [postVeriTel 手机号登录]
     * @param
     * @author [C。]
     * @return json
     */
    public function postVeriTel()
    {
        $param = input('param.');
        $map = [];
        $map['tel'] = $param['tel'];
        $map['code'] = $param['code'];
        $comid = $param['comid'];
        $mem = Db::name('manager')->where('tel',$param['tel'])->find();
        if(empty($mem)){
            writelog($mem['id'],$param['comid'],'手机号不存在！'.$param['tel']);
            return admin_json('-5', '手机号不存在！');
        }
        $result = Db::name('vercode')->where($map)->find();
        if(!empty($result)) {
            if (time() - $result['addtime'] > config('index.code_expiration_time')) {
                return admin_json('-2', '验证码已过期');
            }
            if ($result['status'] == 2) {
                return admin_json('-3', '验证码已使用');
            }
            Db::name('vercode')->where($map)->update(['status' => 2]);
        }else{
            writelog($mem['mid'],$param['comid'],'手机号验证错误！'.$param['tel']);
            return admin_json('-1','手机号或验证码错误');
        }
        $hasUser = Db::name('manager_password')->field('id,mid,tel,password,states,loginnum')->where(['tel'=>$param['tel'],'comid'=>$comid])->find();

        if(empty($hasUser) || $hasUser['states'] == -1){
            return admin_json(-1,'管理员不存在');
        }

        if($hasUser['states'] == 2){
            writelog($hasUser['mid'],$comid,'管理员【'.$hasUser['tel'].'】登录失败：该账号被禁用',-1);
            return admin_json(-7,'该账号被禁用');
        }

        //更新管理员状态
        $data = [
            'loginnum' => $hasUser['loginnum'] + 1,
            'last_login_ip' => request()->ip(),
            'last_login_time' => time(),
            'update_time' => time(),
            'token' => md5($hasUser['tel'] . $hasUser['password'].$comid.time())
        ];

        Db::name('manager_password')->where('id', $hasUser['id'])->update($data);
        writelog($hasUser['mid'],$comid,'管理员【'.$hasUser['tel'].'】登录成功');
        return admin_json(1,'登录成功',['token'=>$data['token']]);
    }
    /**
     * [postEdit  忘记密码]
     * @param
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function postEdit()
    {
        $param = input('param.');
        $model = new ManagerPasswordModel();
        $map = [];
        $map['tel'] = $param['tel'];
        $map['code'] = $param['code'];
        try{
            $manager = Db::name('manager')->field('tel,id')->where('tel',$param['tel'])->find();
            if($manager['tel'] != $param['tel']){
                return admin_json('-2', '手机号必须为本人得！');
            }
            $result = Db::name('vercode')->where($map)->find();
            if(!empty($result)) {
                if (time() - $result['addtime'] > config('index.code_expiration_time')) {
                    return admin_json('-2', '验证码已过期');
                }
                if ($result['status'] == 2) {
                    return admin_json('-3', '验证码已使用');
                }
                Db::name('vercode')->where($map)->update(['status' => 2]);
            }else{
                return admin_json('-1','手机号或验证码错误');
            }

            $mpass = $model->getOne(['comid'=>$param['comid'],'mid'=>$manager['id'],'states'=>1],'id','id,password');
            if(empty($mpass)){
                return admin_json(-1, '您无权限，请联系管理员!');
            }
            $model->editData(['id'=>$mpass['id'],'password'=>md5(md5($param['npassword']) . config('index.manager_password_halt')),'pass'=>$param['npassword']]);
        }catch(\Exception $e){
            systembug($e->getMessage(),3,'index/login/postEdit');
            return admin_json(-1, '修改失败'.$e->getMessage());
        }
        return admin_json(1, '修改成功');
    }
    /**
     * [checkVerify  生成验证码]
     * @author [C。]
     */
    public function getVerify()
    {
        $verify = new Verify();
        $verify->seKey = config('index.verify_halt'); // 自定义验证码加密密钥
        $verify->imageH = 32;
        $verify->imageW = 100;
        $verify->length = 4;
        $verify->useNoise = false; //使用中文验证码
        $verify->fontSize = 14;
        return $verify->entry();
    }
}